﻿using System.Net;
using ScreenWarnning.EventDto;
using ScreenWarnning.Helpers;
using ScreenWarnning.RequestDto;

namespace ScreenWarnning
{
    internal class DataProvider
    {
        private CookieCollection _cookieCollection = new CookieCollection();
        public CookieCollection CookieCollection { get { return _cookieCollection; } }

        private string _host = string.Empty;

        public event EventHandler<DataVItemEventArgs>? OnSucceed;

        public event EventHandler<ExceptionEventArgs>? OnException;

        public event EventHandler<DataGridItemEventArgs>? OnDataGridRefreshed;

        public DataProvider(string host)
        {
            _host = host;
        }

        public void DataV()
        {
            var request = new ApiRequest($"{_host}/wq/admin/dataV/ebigscree/dataGrid", method: RestSharp.Method.Post);
            request.AddCookies(_cookieCollection);
            var ret = request.Invoke();

            if (ret.IsSuccess)
            {
                var items = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DataVItem>>(ret.Data);
                OnSucceed?.Invoke(this, new DataVItemEventArgs(items));
            }
            else
            {
                OnException?.Invoke(this, new ExceptionEventArgs(new Exception(ret.Message)));
            }
        }

        public void DataGrid(DateTime start, DateTime end, int pageNo=1, int pageSize=20)
        {
            var request = new ApiRequest($"{_host}/wq/admin/itemdata/dataGrid", contentType: "application/x-www-form-urlencoded; charset=UTF-8", method: RestSharp.Method.Post);
            request.AddCookies(_cookieCollection);
            var listParam = new List<string>
            {
                $"page={pageNo}",
                $"limit={pageSize}",
                $"license=",
                $"testtype=",
                $"tsno=",
                $"standard=",
                $"result=",
                $"testdate={DateTime.Now:yyyy-MM-dd}",
                $"testdateend={DateTime.Now:yyyy-MM-dd}",
                $"sfdy=",
                $"testtimes=",
                $"testno=",
                $"owner=",
                $"fueltype=",
                $"jclx=",
                $"jczt=",
                $"jcjd=",
                $"testlineno=",
                $"vehicletype=",
                $"vehiclemodel=",
                $"licensecode="
            };
            request.AddBody(string.Join('&',listParam));
            var ret = request.Invoke();
            if (ret.IsSuccess)
            {
                var items = Newtonsoft.Json.JsonConvert.DeserializeObject<DataGridOutput<List<DataGridItem>>>(ret.Data);
                OnDataGridRefreshed?.Invoke(this, new DataGridItemEventArgs(items.Data, items.Count));
            }
            else
            {
                OnException?.Invoke(this, new ExceptionEventArgs(new Exception(ret.Message)));
            }
        }

        public List<WarningItem> ViewWarning(string jylsh,int testtimes)
        {
            var request = new ApiRequest($"{_host}/wq/admin/itemdata/warning/{jylsh}/{testtimes}", method: RestSharp.Method.Get);
            request.AddCookies(_cookieCollection);
            var ret = request.Invoke();

            if (ret.IsSuccess)
            {
                var regex = new System.Text.RegularExpressions.Regex(@"(?<=var resourceWarning = ).*(?=;)");
                var matchRet = regex.Match(ret.Data).Value;
                return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarningItem>>(matchRet);
            }
            else
            {
                OnException?.Invoke(this, new ExceptionEventArgs(new Exception(ret.Message)));
            }
            return null;
        }

        public void Login(string username, string password, string code)
        {
            var request = new ApiRequest($"{_host}/wq/admin/login", contentType: "application/x-www-form-urlencoded; charset=UTF-8", method: RestSharp.Method.Post);
            request.AddBody($"username={System.Web.HttpUtility.UrlEncode(DesHelper.EncryptByDES(username))}&password={System.Web.HttpUtility.UrlEncode(DesHelper.EncryptByDES(MD5Helper.MD5(password)))}&verifycode={System.Web.HttpUtility.UrlEncode(DesHelper.EncryptByDES(code))}");
            request.AddCookies(_cookieCollection);
            var ret = request.Invoke();
            if (!ret.IsSuccess) return;

            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonOutput>(ret.Data);
            if (obj?.Success == true)
            {
                _cookieCollection = request.Client.Options.CookieContainer.GetAllCookies();
                return;
            }
            throw new Exception(obj.Msg);
        }

        public Image GetCode()
        {
            var request = new ApiRequest($"{_host}/wq/front/verify/code/{new Random().NextDouble()}");
            var ret = request.InvokeImage();
            if (ret.IsSuccess) _cookieCollection = request.Client.Options.CookieContainer.GetAllCookies();
            return ret.Data;
        }
    }

    class CommonOutput
    {
        public bool Success { get; set; }

        public string Code { get; set; }

        public string Msg { get; set; }

        public object Obj { get; set; }

        public string EnableOrNot { get; set; }
    }

    class DataGridOutput<T>
    {
        public string Code { get; set; }

        public string Message { get; set; }

        public int Count { get; set; }

        public T Data { get; set; }
    }
}
